#!/bin/bash
shopt -s nullglob

HVNETWORKING=`hvkvp -key PROVISION_NETWORKING`
HVKVP_RESULT=$?

if [ $HVKVP_RESULT -eq 0 ] && [ ! -z "$HVNETWORKING" ]; then
  echo "Hyper-V network configuration available ..."
  echo $HVNETWORKING | base64 --decode > /var/lib/minishift/networking
fi

NETWORK_SCRIPTS=(/var/lib/minishift/networking*)

if [ ${#NETWORK_SCRIPTS[@]} -gt 0 ]; then 

  for FILE in ${NETWORK_SCRIPTS[@]}
  do

    unset DEVICE IPADDR NETMASK GATEWAY DNS1 DNS2 USEDHCP
    echo "Processing network configuration file '$FILE' ..."

    . "$FILE"

    if [ ! -z "$DISABLED" ] || [ -z "$DEVICE" ]; then

       echo "Device is disabled or not set: '$DEVICE'"
       continue

    fi

    echo "Device '$DEVICE' is enabled"
    ip link set dev $DEVICE up

    if [ ! -z "$USEDHCP" ]; then

      echo "Use DHCP for device '$DEVICE'"
      dhclient \
        -pf /var/run/dhclient-$DEVICE.pid \
        -lf /var/lib/dhclient/dhclient-$DEVICE-lease \
        -4 $DEVICE

    else
   
      if [ ! -z "$IPADDR" ] && [ ! -z "$NETMASK" ]; then 
        echo "Set IP address $IPADDR/$NETMASK on device '$DEVICE'"
        ip address add $IPADDR/$NETMASK dev $DEVICE
      fi

      [ ! -z "$GATEWAY" ] && ip route add default via $GATEWAY dev $DEVICE
      [ ! -z "$DNS1" ] && echo "nameserver $DNS1" >  /etc/resolv.conf
      [ ! -z "$DNS2" ] && echo "nameserver $DNS2" >> /etc/resolv.conf

    fi

  done

else

  echo "No network configuration files found"
  systemctl start NetworkManager

fi

exit 0

